from django.http import JsonResponse
from django.shortcuts import render
from apps.sales_man.models import Single
from apps.sales_man.models import ApplicantList
from apps.product.models import Product
from apps.utils.views import apply
from core.tools.wx_session import get_wx_session
from core.tools.wx_login_verify import wx_login
from core.wchat.models import WxUserInfo


@wx_login()
def click_product(request):
    wx_obj = get_wx_session(request)
    openid = wx_obj.openid
    wx_obj = WxUserInfo.objects.get(openid=openid)
    product_id = request.GET.get("id")
    product_obj = Product.objects.get(id=product_id)
    if product_obj.jump_status == 1:
        content = {"url": product_obj.url, "status": "ok"}
        return JsonResponse(content)
    user_info = wx_obj.salesman
    # 如果此用户有身份证号
    if product_obj.is_firm:
        name = request.GET.get("name")
        apply_info = ApplicantList.objects.filter(salesman=user_info,
                                                  name=name)
        if apply_info.exists():
            apply_obj = apply_info.order_by("-id").first()
        else:
            apply_obj = ApplicantList.objects.create(
                salesman=user_info,
                name=name
            )
    else:
        if user_info.card and user_info.tel and user_info.name:
            apply_obj, created = ApplicantList.objects.get_or_create(
                tel=user_info.tel,
                salesman=user_info,
                card=user_info.card,
                name=user_info.name
            )
        # 如果没有身份证号
        else:
            content = {"status": "error", "msg": "请先去‘我的’里更新个人资料"}
            return JsonResponse(content)
    # 2、根据产品 判断是否是思兮类型的产品
    if product_obj.sign_type != 4:  # 如果不是主产品
        # 如果没有子产品
        if product_obj.api_type == 2 and product_obj.sign_type == 2:
            # 如果是思兮API
            status, content = apply(product_obj, apply_obj)
            if status:
                content = {"url": content.get("bank_url"), "status": "ok", "id": product_obj.id}
            else:
                content = {"status": "error", "msg": content.get("message")}
        else:
            # 不是思兮的
            content = {"url": product_obj.url, "status": "ok"}
        Single.objects.create(
            product=product_obj,
            b_user=user_info,
            t_user=user_info.leader,
            applicant=apply_obj,
        )
        return JsonResponse(content)


@wx_login()
def update_show_alter(request):
    wx_obj = get_wx_session(request)
    salesman = wx_obj.salesman
    salesman.show_alert = False
    salesman.save()
    content = {"status": "ok"}
    return JsonResponse(content)


@wx_login()
def show_alter(request):
    wx_obj = get_wx_session(request)
    salesman = wx_obj.salesman
    content = {"show_alert": salesman.show_alert}
    return JsonResponse(content)


def operation_more(request):
    return render(request, "c2c/operation_more.html")
